<template>
  <!-- 添加或修改出货通知单对话框 -->
  <el-dialog :title="title" :visible.sync="open" width="100%" append-to-body :close-on-click-modal="false" v-dialogDrag>
    <div class="app-container" style="display: flex;">
      <el-row style="width: 100%;">
        <el-col :span="6">
          <el-card class="box-card">
            <el-form :model="queryParams" ref="queryForm" size="small" v-show="showSearch" label-width="98px">
              <el-form-item label="买方" prop="customerId">
                <el-select style="width: 100%;" v-model="queryParams.params['customId']" placeholder="请选择买方" filterable
                  @change="selectCustomerQuery" clearable>
                  <el-option v-for="dict in dict.type.goods_customer" :key="dict.value"
                    :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="订单编号" prop="projectNo">
                <el-input v-model="queryParams.projectNo" placeholder="请输入订单编号" clearable
                  @keyup.enter.native="handleQuery" />
              </el-form-item>
              <el-form-item label="产品编码" prop="goodsCode">
                <el-input v-model="queryParams.goodsCode" placeholder="请输入产品编码" clearable
                  @keyup.enter.native="handleQuery" />
              </el-form-item>
              <el-form-item label="产品名称" prop="goodsName">
                <el-input v-model="queryParams.goodsName" placeholder="请输入产品名称" clearable
                  @keyup.enter.native="handleQuery" />
              </el-form-item>
              <el-form-item label="产品型号" prop="goodModel">
                <el-input v-model="queryParams.goodModel" placeholder="请输入产品型号" clearable
                  @keyup.enter.native="handleQuery" />
              </el-form-item>
              <el-form-item label="客户编码" prop="customerCode">
                <el-input v-model="queryParams.params['customerCode']" placeholder="请输入客户编码" clearable
                  @keyup.enter.native="handleQuery" />
              </el-form-item>
              <el-form-item label="项目单位" prop="companyName">
                <el-input v-model="queryParams.params['companyName']" placeholder="请输入项目单位" clearable
                  @keyup.enter.native="handleQuery" />
              </el-form-item>
              <el-form-item label="工程名称" prop="gongchengName">
                <el-input v-model="queryParams.gongchengName" placeholder="请输入工程名称" clearable
                  @keyup.enter.native="handleQuery" />
              </el-form-item>
              <el-form-item label="下单日期" prop="orderDate">
                <el-date-picker  v-model="queryParams.params['orderDate']" placeholder="请选择下单日期"  type="date" value-format="yyyy-MM-dd" clearable
                          @keyup.enter.native="handleQuery" />
              </el-form-item>
              <el-form-item label="业务员" prop="salesmanName">
                <el-input v-model="queryParams.params['salesmanName']" placeholder="请输入业务员" clearable
                  @keyup.enter.native="handleQuery" />
              </el-form-item>
              <el-form-item label="制单人" prop="goodModel">
                <el-input v-model="queryParams.params['createName']" placeholder="请输入制单人" clearable
                  @keyup.enter.native="handleQuery" />
              </el-form-item>
              <el-form-item label="合同收货人" prop="deliveryPerson">
                <el-input v-model="queryParams.deliveryPerson" placeholder="请输入合同收货人" clearable
                  @keyup.enter.native="handleQuery" />
              </el-form-item>
              <div style=" display: flex;align-items: center;margin-bottom: 10px;">
                <div style=" display: flex;margin-left: auto;">
                  <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                  <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                  <el-button type="primary" size="mini" @click="submitForm">添 加</el-button>
                </div>
              </div>
            </el-form>
            <el-form ref="form" :model="form" :rules="rules" label-width="98px">
              <el-form-item label="发货通知编码" prop="nos">
                <el-input v-model="form.nos" placeholder="请输入发货通知编码" disabled />
              </el-form-item>
              <el-form-item label="买方" prop="kehuId">
                <el-select v-model="form.kehuId" placeholder="请选择买方" filterable @change="selectCustomer" clearable
                  style="width: 100%">
                  <el-option v-for="dict in dict.type.goods_customer" ref="myselectCustomer" :key="dict.value"
                    :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="联系人" prop="linkman">
                  <el-input v-model="form.linkman" placeholder="请输入联系人"/>
                <!--<el-select v-model="form.linkman" placeholder="请选择联系人" filterable @change="selectShouhuoren" clearable
                  style="width: 100%">
                  <el-option ref="myselectShouhuoren" v-for="it in this.columnsLinkman" :key="it.shouhuoren" :value="it"
                    :label="it.shouhuoren">
                  </el-option>
                </el-select>-->
              </el-form-item>
              <el-form-item label="联系电话" prop="linktel">
                <el-input style="width: 100%;" v-model="form.linktel" placeholder="请输入联系电话" />
              </el-form-item>
              <el-form-item label="交货日期" prop="jiaohuoDate">
                <el-date-picker style="width: 100%;" clearable v-model="form.jiaohuoDate" type="date"
                  value-format="yyyy-MM-dd" placeholder="请选择交货日期">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="业务经理及电话" prop="jingli">
                <el-input v-model="form.jingli" placeholder="请输入业务经理及电话" />
              </el-form-item>
              <el-form-item label="收货地址" prop="address">
                <el-input v-model="form.address" placeholder="请输入收货地址" />
              </el-form-item>
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" placeholder="请输入备注" />
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>
        <el-col :span="18">
          <el-card class="box-card" style="margin-left: 10px;">
            <el-form ref="formList" :model="form" label-width="120px">
              <el-table border v-loading="loading" :data="columns" @selection-change="handleSelectionChange" max-height="100%" @sort-change="handleSortChange">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column sortable label="买方" align="center" prop="order.customName" show-overflow-tooltip />
                <el-table-column sortable label="客户编码" align="center" prop="order.customerCode" show-overflow-tooltip />
                <el-table-column sortable label="订单编号" align="center" prop="projectNo" show-overflow-tooltip />
                <el-table-column sortable label="发货状态" align="center" prop="isfahuo" show-overflow-tooltip>
                  <template slot-scope="scope">
                    <dict-tag :options="dict.type.yifahuo_status" :value="scope.row.isfahuo" />
                  </template>
                </el-table-column>
                <el-table-column sortable label="合同收货人" align="center" prop="deliveryPerson" show-overflow-tooltip />
                <el-table-column sortable label="下单日期" align="center" prop="order.orderDate" show-overflow-tooltip />
                <el-table-column sortable label="产品编码" align="center" prop="goodsCode" show-overflow-tooltip />
                <el-table-column sortable label="产品名称" align="center" prop="goodsName" show-overflow-tooltip />
                <el-table-column sortable label="产品型号" align="center" prop="goodModel" show-overflow-tooltip />
                <el-table-column sortable label="工程名称" align="center" prop="gongchengName" show-overflow-tooltip />
                <el-table-column sortable label="项目单位" align="center" prop="order.companyName" show-overflow-tooltip />
                <el-table-column sortable label="业务员" align="center" prop="order.salesmanName" show-overflow-tooltip />
                <el-table-column sortable label="制单人" align="center" prop="order.createName" show-overflow-tooltip />
                <el-table-column label="订单数量" align="center" prop="orderCount" show-overflow-tooltip />
                <el-table-column label="剩余发货数量" align="center" prop="fahuoShengyu" show-overflow-tooltip />
                <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip>
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.remark"></el-input>
                  </template>
                </el-table-column>
              </el-table>
            </el-form>
            <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize" @pagination="getList" />
          </el-card>
          <el-card class="box-card" style="margin-left: 10px;margin-top: 10px;">
            <el-table :data="columns2" ref="dragTable" row-key="id" v-loading="loading2" @sort-change="handleSortChange1" max-height="550">
              <el-table-column sortable label="买方" align="center" prop="order.customName" show-overflow-tooltip />
              <el-table-column sortable label="客户编码" align="center" prop="order.customerCode" show-overflow-tooltip />
              <el-table-column sortable label="订单编号" align="center" prop="proNo" show-overflow-tooltip />
              <el-table-column sortable label="产品编码" align="center" prop="nos" show-overflow-tooltip />
              <el-table-column sortable label="产品名称" align="center" prop="name" show-overflow-tooltip />
              <el-table-column sortable label="产品型号" align="center" prop="models" show-overflow-tooltip />
              <el-table-column label="产品单位" align="center" prop="danwei" show-overflow-tooltip />
              <el-table-column label="产品单价" align="center" prop="danjian" show-overflow-tooltip />
              <el-table-column label="预发货数量" align="center" prop="shuliang" show-overflow-tooltip />
              <el-table-column label="业务员" align="center" prop="shuliang" show-overflow-tooltip />
              <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip />
              <el-table-column align="center" class-name="small-padding fixed-width" label="操作" width="140">
                <template slot-scope="scope">
                  <!-- <el-button size="mini" type="text" icon="el-icon-edit" @click="showChild(scope.row)">发货通知明细</el-button>-->
                  <el-popconfirm :title="`确认删除 `+scope.row.name+` 数据项？`" @confirm="handleDelete(scope.row)"
                    style="margin-left: 10px;">
                    <el-button icon="el-icon-delete" size="mini" slot="reference" type="text"
                      v-hasPermi="['develop:ProjectBaseInfo:remove']">删除
                    </el-button>
                  </el-popconfirm>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitFormFahuodan">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import {
    getAction,
    addAction,
    getById,
    deleteAction
  } from '@/api/manage';
  import moment from 'moment';

  export default {
    name: "LvFahuotongzhiForm",
    dicts: ['goods_customer', 'yifahuo_status'],
    data() {
      return {
        // 遮罩层
        loading: true,
        loading2: false,
        activeName: "first",
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          kehuId: [{
            required: true,
            message: "买方不能为空",
            trigger: "blur"
          }],
          /*linkman: [{
            required: true,
            message: "联系人不能为空",
            trigger: "blur"
          }],
          linktel: [{
            required: true,
            message: "联系电话不能为空",
            trigger: "blur"
          }],*/
        },
        total: 0,
        total2: 0,
        // 入库信息管理表格数据
        dataList: [],
        columns: [],
        columns2: [],
        columnsLinkman: [],
        showSearch: true,
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          goodsCode: null,
          goodsName: null,
          goodModel: null,
          brand: null,
          projectName: null,
          projectNo: null,
          isfahuo: "0",
         // isdo: "0",
          params: {},
          customerCode: null,
          createName: null,
          salesmanName: null,
          orderDate: null,
          companyName: null,
          customName: null,
          deliveryPerson: null,
        },
        queryParams2: {
          pageNum: 1,
          pageSize: 1000,
          params: {},
          id: null,
          name: null,
          model: null,
          brand: null,
          isFahuo: "0",
          customerCode: null,
          createName: null,
          salesmanName: null,
          orderDate: null,
          createBy: this.$store.getters.name,
        },
        queryParamsLinkman: {
          pageNum: 1,
          pageSize: 20000,
          customId: null,
          customerCode: null,
          createName: null,
          salesmanName: null,
          orderDate: null,
          name: null,
          params: {},
        },
        url: {
          listSale: '/goodsSale/goodsSale/list',
          list2: '/lvFahuomingxi/lvFahuomingxi/list',
          getById: '/lvFahuotongzhi/lvFahuotongzhi/',
          insertForTzd: '/lvFahuotongzhi/lvFahuotongzhi/insertForTzd',
          edit: '/lvFahuotongzhi/lvFahuotongzhi/edit',
          add: '/lvFahuotongzhi/lvFahuotongzhi/add',
          remove2: '/lvFahuomingxi/lvFahuomingxi/removeFhtz/',
          listLinkman: '/goodsShouhuoren/goodsShouhuoren/list',
        },
      };
    },
    created() {
    },
    methods: {

      selectCustomerQuery(value) {
        // this.form.kehuId = value;
        this.queryParams2.params['kehuId'] = value;
        this.getList();
        this.selectCustomer(value);
        this.handleQuery()
      },

      selectCustomer(value) {
        let that = this;
        that.queryParams2.params['kehuId'] = value;
        // that.getList2();
        that.$nextTick(() => {
          let arr = that.$refs.myselectCustomer;
          for (let i = 0; i < arr.length; i++) {
            if (arr[i].currentValue == value) {
              that.form.kehuName = arr[i].label;
              that.queryParamsLinkman.customId = value;
              getAction(this.url.listLinkman, this.queryParamsLinkman).then(response => {
                this.columnsLinkman = response.rows;
              });
            }
          }
          that.form.linkman = '';
          that.form.linktel = '';
          that.form.jingli = '';
          that.form.address = '';
        })
      },
      selectShouhuoren(value) {
        let that = this;
        that.$nextTick(() => {
          let arr = that.$refs.myselectShouhuoren;
          for (let i = 0; i < arr.length; i++) {
            if (arr[i].currentValue == value) {
              that.form.linkman = value.shouhuoren;
              that.form.linktel = value.shouhuotel;
              that.form.jingli = value.jingli;
              that.form.address = value.address;
            }
          }
        })
      },
      updateTotleCost(row) {
        let that = this;
        if (row.shengyu && row.goodsBuyPrice) {
          let totleCost = that.functionNumberMul(row.shengyu, row.goodsBuyPrice);
          that.$set(row, "goodsBuyTotal", totleCost);
        }
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          delFlag: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          remark: null,
          nos: null,
          name: null,
          jiaohuoDate: null,
          linkman: null,
          linktel: null,
          address: null,
          status: "0",
          state: "0",
          jingli: null,
          kehuId: null,
          kehuName: null,
          taxNo: null,
          taxCode: null,
          taxDate: null,
          taxMoney: null,
          taxShengyu: null,
          taxAllmoeny: null,
          allMoney: null,
          shengyu: null,
          yihui: null
        };
        this.resetForm("form");
      },
      getList() {
        this.loading = true;
        getAction(this.url.listSale, this.queryParams).then(response => {
          let res = response.rows;
          this.columns = res;
          this.total = response.total;
          this.loading = false;
        });
      },
      getList2() {
        this.loading2 = true;
        getAction(this.url.list2, {
          pageNum: this.queryParams2.pageNum,
          pageSize: this.queryParams2.pageSize,
          id: this.queryParams2.id,
          name: this.queryParams2.name,
          model: this.queryParams2.model,
          brand: this.queryParams2.brand,
          isFahuo: this.queryParams2.isFahuo,
          createBy: this.queryParams2.createBy,
        }).then(response => {
          this.columns2 = response.rows;
          this.total2 = response.total;
          this.loading2 = false;
        });
      },
      /** 排序触发事件 */
      handleSortChange(column, prop, order) {
      this.queryParams.orderByColumn = column.prop;
      this.queryParams.isAsc = column.order;
      this.handleQuery();
    },
    /** 排序触发事件 */
    handleSortChange1(column, prop, order) {
      this.queryParams2.orderByColumn = column.prop;
      this.queryParams2.isAsc = column.order;
      this.handleQuery2();
    },

      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 搜索按钮操作 */
      handleQuery2() {
        this.queryParams2.pageNum = 1;
        this.getList2();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.queryParams.params = {};
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.dataList = selection;
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加出货通知单";
        this.loading = false;
        /*     function formatDateTime(date) {*/
        var date = new Date();
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        //const milliseconds = String(date.getMilliseconds()).padStart(3, '0');
        this.form.nos = "" + year + month + day + hours + minutes + seconds;
        //return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}.${milliseconds}`;
        this.getList()
        this.getList2()
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids;
        getById(this.url.getById, id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改出货通知单";
        });
      },
      /** 提交按钮 */
      submitFormFahuodan() {
        // console.log(this.form.kehuId);
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (!this.columns2.length) {
              this.$modal.msgError("请选择一条记录");
            } else if (!this.columns2.every(obj => obj.order.customId === this.columns2[0].order.customId)) {
              this.$modal.msgError("多买家信息不一致，请检查");
            } else if (this.columns2.find(item => item.order.customId != this.form.kehuId)) {
              this.$modal.msgError("选中买家信息与表买家信息不一致，请检查");
            } else {
              if (this.form.id != null) {
                updateAction(this.url.edit, this.form).then(response => {
                  this.$modal.msgSuccess("修改成功");
                  this.open = false;
                  this.getList2()
                  this.$emit('ok');
                });
              } else {
                console.log(this.form)
                addAction(this.url.add, this.form).then(response => {
                  this.$modal.msgSuccess("新增成功");
                  this.open = false;
                  this.getList2()
                  this.$emit('ok');
                });
              }
            }
          }
        });
      },
      submitForm() {
        let that = this;
        const ids = this.ids;
        const allEqual = arr => arr.every(val => val === arr[0]);
        const customId = []
        for (var i in ids) {
          customId.push(this.columns.find(item => item.id == ids[i]).order.customId)
        }
        const customName = []
        for (var i in ids) {
          customName.push(this.columns.find(item => item.id == ids[i]).order.customName)
        }
        console.log(customName, allEqual(customName),'customNamecustomNamecustomNamecustomName');
        if (ids == null || ids == '' || ids == 'undefined') {
          that.$modal.msgError("请选择一条记录");
          // alert("请选择一条记录");
        } else if (!allEqual(customId)) {
          that.$modal.msgError("多买家信息不一致，请检查");
        } else {
          that.$refs["formList"].validate(valid => {
            if (valid) {
              const fahuomingxi = Object.assign({});
              fahuomingxi.columns = that.dataList;
              that.form.kehuName = that.columns[0].kehuName

              addAction(that.url.insertForTzd, fahuomingxi).then(response => {
                that.$modal.msgSuccess("添加成功");
                that.handleQuery();
                that.handleQuery2();
                that.$emit('ok');
                that.form.kehuName = customName[0];
                that.form.kehuId = customId[0];
                that.form.linkman = '';
                that.form.linktel = '';
                that.form.jingli = '';
                that.form.address = '';
              });
            }
          });
        }
      },
      handleDelete(row) {
        const id = row.id;
        deleteAction(this.url.remove2, id).then(response => {
          this.$modal.msgSuccess("删除成功");
          this.handleQuery();
          this.handleQuery2();
        }).catch(() => {});
      },
    }
  };
</script>
